import { Button, Dropdown, Input, Layout, Menu, Typography } from 'antd';
import type { MenuProps } from 'antd';
import { JwtPayload as DefaultJwtPayload, jwtDecode } from 'jwt-decode';
import React, { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useDispatch } from 'react-redux';
import { useHistory } from 'react-router-dom';

import logo from '../../logo.svg';
import { useSelector } from '../../redux/hooks';
import {
  addLanguageActionCreator,
  changeLanguageActionCreator
} from '../../redux/language/language-acitons';
import { userSlice } from '../../redux/user/slice';
import styles from './header.module.css';

type MenuItem = Required<MenuProps>['items'][number];
const menuItems: MenuItem[] = [
  {
    label: '旅游首页',
    key: '1'
  },
  {
    label: '周末游',
    key: '2'
  },
  {
    label: '跟团游',
    key: '3'
  },
  {
    label: '周末游',
    key: '4'
  },
  {
    label: '跟团游',
    key: '5'
  },
  {
    label: '自由行',
    key: '6'
  },
  {
    label: '私家团',
    key: '7'
  },
  {
    label: '邮轮',
    key: '8'
  },
  {
    label: '酒店+景点',
    key: '9'
  },
  {
    label: '当地玩乐',
    key: '11'
  },
  {
    label: '主题游',
    key: '12'
  },
  {
    label: '定制游',
    key: '13'
  },
  {
    label: '游学',
    key: '14'
  },
  {
    label: '签证',
    key: '15'
  },
  {
    label: '企业游',
    key: '16'
  },
  {
    label: '高端游',
    key: '17'
  },
  {
    label: '爱玩户外',
    key: '18'
  },
  {
    label: '保险',
    key: '19'
  }
];
interface JwtPayload extends DefaultJwtPayload {
  username: string;
}

export const Header: React.FC = () => {
  const history = useHistory();
  const { t } = useTranslation();

  // 获取数据
  const language = useSelector((state) => state.language.language);
  const languageList = useSelector((state) => state.language.languageList);

  const jwt = useSelector((s) => s.user.token);

  const [username, setUsername] = useState('');
  useEffect(() => {
    if (jwt) {
      const token = jwtDecode<JwtPayload>(jwt);
      setUsername(token.username);
    }
  }, [jwt]);
  // 分发数据
  // 如果需要定义类型的话，但是没必要 const dispatch = useDispatch<Dispatch<LanguageActionTypes>>()
  const dispatch = useDispatch();
  const menuClickHandler = (e) => {
    if (e.key === 'new') {
      const action = addLanguageActionCreator(`new_lang${Date.now()}`, `新语言${Date.now()}`);
      dispatch(action);
    } else {
      const action = changeLanguageActionCreator(e.key);
      dispatch(action);
    }
  };

  const onLogout = () => {
    dispatch(userSlice.actions.logOut());
    history.push('/');
    window.location.reload();
  };
  return (
    <div>
      <div className={styles['top-header']}>
        <div className={styles['inner']}>
          <div className={styles['inner-left']}>
            <div className={styles['inner-left-label']}>让旅游更幸福</div>
            <Dropdown
              placement="bottom"
              dropdownRender={() => (
                <Menu onClick={menuClickHandler}>
                  {languageList.map((item) => {
                    return <Menu.Item key={item.code}>{item.name}</Menu.Item>;
                  })}
                  <Menu.Item key={'new'}>添加新语言</Menu.Item>
                </Menu>
              )}
            >
              <Button>{language === 'zh' ? '中文' : 'English'}</Button>
            </Dropdown>
          </div>
          {jwt ? (
            <Button.Group className={styles['button-group']}>
              <span>
                {t('header.welcome')}
                <Typography.Text strong>{username}</Typography.Text>
              </span>
              <Button> {t('header.shoppingCart')}</Button>
              <Button onClick={onLogout}> {t('header.signOut')}</Button>
            </Button.Group>
          ) : (
            <Button.Group className={styles['button-group']}>
              <Button onClick={() => history.push('/register')}> {t('header.register')}</Button>
              <Button onClick={() => history.push('/signIn')}> {t('header.signin')}</Button>
            </Button.Group>
          )}
        </div>
      </div>
      <Layout.Header className={styles['main-header']}>
        <div>
          <img src={logo} alt="logo" className={styles['app-logo']} />
          <Typography.Title level={3} className={styles['title']}>
            React.旅游网
          </Typography.Title>
        </div>
        <Input.Search placeholder="Basic usage" className={styles['search-input']} />
      </Layout.Header>
      <Menu mode="horizontal" className={styles['main-menu']} items={menuItems} />;
    </div>
  );
};
